import Base from "./base";
const tableName = `admin_user`;
export default class extends Base {
  static get _REST() {
    return true;
  }
  async postAction() {
    console.log("进入这里223");
    const username = this.post("username");
    const password = this.post("password");
    console.log(username, password);
    const admin = await this.model(tableName)
      .where({ username: username })
      .find();
    console.log(admin);
    if (think.isEmpty(admin)) {
      return this.fail(403, "用户名或密码不正确1");
    }
    console.log(think.md5(password));
    if (think.md5(password) !== admin.password) {
      return this.fail(400, "用户名或密码不正确2");
    }
    // 更新登录信息
    var now = this.getDateTime();
    await this.model(tableName).where({ id: admin.id }).update({
      login_time: now,
      login_ip: this.ctx.ip,
    });
    // 生成token
    const TokenSerivce = this.service("token", "admin");
    const sessionKey = await TokenSerivce.create({
      user_id: admin.id,
    });
    if (think.isEmpty(sessionKey)) {
      return this.fail("登录失败");
    }

    const userInfo = {
      id: admin.id,
      username: admin.username,
      avatar: admin.avatar,
      admin_role_id: admin.admin_role_id,
    };

    return this.success({ token: sessionKey, ...userInfo });
  }
}
